package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private JedisPool jedisPool;
   @Reference
    private MemberService memberService;
   //手机号快速登录
   @RequestMapping("/login")
   public Result login(HttpServletResponse response, @RequestBody Map map){
       //判断验证码是否正确
       String telephone = (String) map.get("telephone");
       String validateCode = (String) map.get("validateCode");
       //从redis中获取验证码
       String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
       if (validateCodeInRedis!=null&&validateCode!=null&&validateCode.equals(validateCodeInRedis)) {
           //验证用过判断用户是否已经注册
           Member member = memberService.findByTelephone(telephone);
           if (member ==null) {
               //不是会员,将此信息添加为会员
               member.setRegTime(new Date());
               member.setPhoneNumber(telephone);
               memberService.add(member);
           }
           //向客户端添加cookie,为了登录验证,值为手机号
           Cookie cookie = new Cookie("login_member_telephone",telephone);
           cookie.setPath("/");//cookie的跨域,加了/ 表示所有的地方都可以获取到cookie,如果时("/webinfo_b")则之恶能在此文件下的文件访问到cookie
           cookie.setMaxAge(60*60);
           response.addCookie(cookie);
           //将会员信息保存到redis中(这里是代替了session,因为session在分布式或者集群中无法获取,有局限性)
           //将会员信息对象变成String(String类型字符串)
           String json = JSON.toJSON(member).toString();
           //存到redis中
           jedisPool.getResource().setex(telephone,60*30,json);
           return new Result(true,MessageConstant.LOGIN_SUCCESS);

       }else{
           //输入的验证码错误
           return new Result(false, MessageConstant.VALIDATECODE_ERROR);
       }
   }
}
